package com.ruoyi.stock2.config;


import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Receivemail {

    static Map<String, String>  map = new HashMap(100);
    public static void main(String[] args) throws Exception {
        while (true){
            pop3test();
            Thread.sleep(2000);
        }


    }
    public static void pop3test() throws Exception {
        // 定义连接POP3服务器的属性信息
        String pop3Server = "mail.sic-ca.com";
        String protocol = "imap";
        String username = "mutou@sic-ca.com";
        String password = "a123456_"; // QQ邮箱的SMTP的授权码，什么是授权码，它又是如何设置？

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol); // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.imap.host", pop3Server); // 发件人的邮箱的 SMTP服务器地址

        // 获取连接
        Session session = Session.getInstance(props);
        session.setDebug(false);

        // 获取Store对象
        Store store = session.getStore(protocol);
        store.connect(pop3Server, username, password); // POP3服务器的登陆认证

        // 通过POP3协议获得Store对象调用这个方法时，邮件夹名称只能指定为"INBOX"
        Folder folder = store.getFolder("INBOX");// 获得用户的邮件帐户
        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限

        Message[] messages = folder.getMessages(folder.getMessageCount()-folder.getUnreadMessageCount()+1,folder.getMessageCount());// 得到邮箱帐户中的所有邮件

        for (Message message : messages) {
            String subject = "";
            try {
                subject = message.getSubject();// 获得邮件主题
                Address from = (Address) message.getFrom()[0];// 获得发送者地址
                Flags flags = message.getFlags();
                if (flags.contains(Flags.Flag.SEEN))
                    System.out.println("这是一封已读邮件");
                else {
                    System.out.println("未读邮件");
                }

                System.out.println("邮件的主题为: " + subject);
                if(subject.startsWith("获取D盘文件目录") && map.get(subject)==null){

                    try {
                        List<String> list = OtherUtils.exec("cmd /c dir d:");
                        StringBuffer stringBuffer = new StringBuffer();
                        for (String str : list){
                            System.out.println(str);
                            stringBuffer.append(str).append("\r\n");
                        }
                        sendmail("发送结果", stringBuffer.toString(), from.toString());
                        map.put(subject, "1");
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }catch (MessageRemovedException exception){
                exception.printStackTrace();
            }
        }

        folder.close(true);// 关闭邮件夹对象
        store.close(); // 关闭连接对象

    }


    public static void sendmail(String subject, String content, String email){
// 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        String from = "mutou@sic-ca.com";// 发件人电子邮箱
        String host = "mail.sic-ca.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

        Properties properties = System.getProperties();// 获取系统属性

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        try {
            //QQ邮箱需要下面这段代码，163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            // 1.获取默认session对象
            Session session = Session.getInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("mutou@sic-ca.com", "a123456_"); // 发件人邮箱账号、授权码
                }
            });


            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject(subject);

            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);

            System.out.println("邮件成功发送!");



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}